<?php
namespace app\controller;

use app\Controller;
use app\model\User as Model;
use EasyWeChat\Factory;
use app\helper\Ident;
use app\helper\BizCrypt;

class Weapp extends Controller
{
    /**
     * 小程序绑定
     * 
     * @return array
     */
    public function bind()
    {
        $post = $this->request->post();
        $model = Model::wehre('mobile', $post['account'])->findOrEmpty();
        $model->save($post);
        // 获取token
        $data = ['access_token' => Ident::token(['id' => $model->id, 'idcard' => $model->idcard]), 'id' => $model->id]; //参数为用户认证的信息，请自行添加
        redis()->hset('AccessTokenList', $data['access_token'], $data + ['login_at' => time()]);
        return json($data);
    }
    /**
     * 密码登录.
     * 
     */
    public function login()
    {
        $post = $this->request->post();
        $model = Model::where('mobile', $post['account'])->findOrEmpty();

        if (!$model->isEmpty() && $model->status !== 2) {
            return ['code' => 0, 'msg' => '账号异常!'];
        }

        $model->save(['status' => 2] + $post);

        $wechat = UserThird::where([['user_id', '=', $model->id], ['type', '=', 1]])->findOrEmpty();
        $wechat->save(['user_id' => $model->id, 'openid' => $post['openid'], 'type' => 1]);

        $data = ['token' => Ident::token(['uid' => $model->id, 'account' => $model->mobile, 'openid' => $post['openid']]), 'id' => $model->id]; //参数为用户认证的信息，请自行添加
        redis()->hset('AccessTokenList', $data['token'], $data + ['openid' => $model->openid, 'mobile' => $model->mobile, 'login_at' => time()]);

        return json($data + [
            'is_auth' => !empty($model->mobile),
            'nickname' => $post['nickname'] ?? '',
            'avatar' => $post['avatar'] ?? '',
        ]);
    }
    /**
     * 获取小程序session
     *
     * @return void
     */
    public function session()
    {
        $app = Factory::miniProgram(config('wechat.mini'));
        $response = $app->auth->session(input('get.code/s'));
        session('weapp_session_key', $response['session_key']);
        session('weapp_openid', $response['openid']);

        return json($response);
    }
    /**
     * 小程序解密
     *
     * @return void
     */
    public function decode()
    {
        $crypt = new BizCrypt();
        return json($crypt->decode(input('post.data/s'), input('post.session_key/s'), input('post.iv/s')));
    }
}
